package com.engc.common.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;

import javax.activation.MimetypesFileTypeMap;


public class UploadFile {
	/* 
	 * Java文件操作 获取文件扩展名 
	 * 
	 *  Created on: 2011-8-2 
	 *      Author: blueeagle 
	 */  
	    public static String getExtensionName(String filename) {   
	        if ((filename != null) && (filename.length() > 0)) {   
	            int dot = filename.lastIndexOf('.');   
	            if ((dot >-1) && (dot < (filename.length() - 1))) {   
	                return filename.substring(dot + 1);   
	            }   
	        }   
	        return filename;   
	    }  
	
	private boolean uploadFile(String type, String file_name) {
	    URL url = null;
	    HttpURLConnection hc = null;
	    byte[] raw = null;
	    FileInputStream in = null;
	    File file = null;
	    try {
	        file = new File(file_name);
	        long file_size = 0;
	        if (file.exists()) {
	            file_size = file.length();
	        }
	        in = new FileInputStream(file_name);
	        raw = new byte[Integer.parseInt(String.valueOf(file_size))];
	 
	        int i = 0;
	        int index = 0;
	        while ((i = in.read()) != -1) {
	            raw[index++] = (byte) i;
	        }
	    } catch (IOException e) {
	        e.printStackTrace();
	        return false;
	    } finally {
	        try {
	            if (in != null) {
	                in.close();
	            }
	        } catch (Exception e) {
	        }
	    }
	    System.out.println(file.getName());
	 
	    MimetypesFileTypeMap file_type_map = new MimetypesFileTypeMap();
	    String mine_type = file_type_map.getContentType(file);
	    System.out.println(mine_type);
	    
	    String filename=file.getName();
	    String remoe_folder="/";
	    String filetype=getExtensionName(filename);
	    remoe_folder=remoe_folder+filename;
	    
	    System.out.println(filetype);
	    System.out.println(remoe_folder);
	    String remoe_up_http_url = "";
	 
	    try {
	        remoe_up_http_url = "http://localhost:8090/upload?Command=FileUpload&Type="
	                + filetype
	                + "&fileName="
	                + URLEncoder.encode(remoe_folder, "UTF-8");
	        url = new URL(remoe_up_http_url);
	        //String BOUNDARY = "---------------------------7d33a816d302b6"; // separate line
	  //      String BOUNDARY="";
	//        String MULTIPART_FORM_DATA = "multipart/form-data";
//	        StringBuffer sb = new StringBuffer();
//	        sb = sb.append("--");
//	        sb = sb.append(BOUNDARY);
//	        sb = sb.append("\r\n");
//	        //sb = sb
//	        //        .append("Content-Disposition:form-data;name=\"NewFile\";filename=\""
//	       //                 + file_name + "\"\r\n");
//	       // sb = sb.append("Content-Type:");
//	        //sb = sb.append(mine_type);
//	        sb = sb.append("\r\n\r\n");
//	        byte[] data = sb.toString().getBytes("UTF-8");
//	        byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
	        hc = (HttpURLConnection) url.openConnection();
//	        // set HTTP head:
//	        hc.setRequestProperty("Content-Type", MULTIPART_FORM_DATA
//	                + ";boundary=" + BOUNDARY);
//	        hc.setRequestProperty("Content-Length", String.valueOf(data.length
//	                + raw.length + end_data.length));
	        hc.setRequestMethod("POST");
	        hc.setDoOutput(true);
	        hc.setDoInput(true);
	        //hc.getOutputStream().write(data);
	        hc.getOutputStream().write(raw, 0, raw.length);
	       // hc.getOutputStream().write(end_data);
	        hc.getOutputStream().close();
	        int cah = hc.getResponseCode();
	        System.out.println(cah);
//          System.out.println(cah);
//	        if (cah != HttpURLConnection.HTTP_OK) {
//	            System.out.println(cah);
//	            return false;
//	        }
	        // 定义输入流
//	        InputStream instream = hc.getInputStream();
//	        BufferedReader br = new BufferedReader(new InputStreamReader(
//	                instream, "UTF-8"));
//	        String content = "";
//	        String line = br.readLine();
//	        while (line != null) {
//	            content += line + "\n";
//	            line = br.readLine();
//	        }
//	        System.out.println(content);
//	        if (content
//	                .indexOf("window.parent.frames['frmUpload'].OnUploadCompleted(203,") > 0) {
//	            //上传失败
//	            return false;
//	        }
//	        
	        
	        String path= "http://172.16.17.27:8090"+remoe_folder;
	        return true;
	    } catch (Exception e) {
	        e.printStackTrace();
	        return false;
	    } finally {
	        try {
	            hc.getOutputStream().close();
	        } catch (Exception e) {
	 
	        }
	        hc.disconnect();
	    }
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		UploadFile test= new UploadFile();
		String file_name="D:\\1.jpg";
		System.out.println(test.uploadFile("jpg", file_name));	
	}

}
